import os
from django.shortcuts import render,HttpResponse,redirect
from .models import Student
from student_mg.settings import STATIC_URL
from django.core.paginator import  Paginator


def index(request):
    return HttpResponse("dsda")

def stu_add(request):
    if request.method=='GET':
        return render(request,'add.html')
    if request.method=='POST':
        name=request.POST.get('name')
        sex=request.POST.get('sex')
        stu_class=request.POST.get('stu_class')
        specialized=request.POST.get('specialized')
        head_img=request.FILES.get('head')
        #添加到数据库 去重
        try:
            Student.objects.get_or_create(stu_name=name,sex=sex,stu_class=stu_class,specialized=specialized,img_path=head_img.name)
        except Exception as f:
            return HttpResponse('报错了')
        #下载图片
        try:
            with open(os.path.join(STATIC_FLELDS[0],head_img.name),'wb')as f:
                for data in head_img.chunks():
                    f.write(data)
        except Exception as s:
            raise s
        return HttpResponse('上传成功')

def stuList(request):
    stu=Student.objects.all()
    pageNum=request.GET.get('page')
    page=Paginator(stu,3)
    stuinfo=page.get_page(pageNum)


def del_stu(request,id):
    #查到直接删除
    try:
        Student.objects.get(id=id).delete()
    except Exception as f:
        return  HttpResponse('删除失败')
    return redirect('stu:stulist')

def get_stu(request):
    s=Student.objects.get(id=id)
    return render(request,'stu_info.html',{'info':s})





